<?php
/**
 * 作者:晨光
 * EMAIL:461718846@qq.com
 * DATE:2020/4/29
 */

namespace app\common\taglib;

use app\common\model\Dictionary;
use think\template\TagLib;

class Rdf extends TagLib
{
    /**
     * 定义标签列表
     */
    protected $tags   =  [
        /**标签定义
         * attr：属性列表
         * close：是否闭合（0表示闭合，1表示不闭合。默认值为1）
         * alias：标签别名
         * level：嵌套层次
         */
        'dic'     => ['attr' => 'code,type,default,name,required,class','close'=>0],

    ];

    /**
     * 字典表标签
     * 格式：{rdf:dic name='sex' code='sex' type='radio' default='$admin.sex' required='required' class='sex1' /}
     * code 字典表编码
     * name 生成的表单元素name值
     * type 支持的表单 select-下拉 radio-单选 checked-多选
     * default 默认值 如果是多选的话可以是字符串 1,2,3,4
     * required 是否必填，此项只适用于layui表单，其余表单自己写必填
     * class 表单元素的class值，一般用于样式美化，内容校验
     * $tag：存放标签属性的数组
     */
    public function tagDic($tag)
    {
        $code = isset($tag['code'])?$tag['code']:'';
        $type = isset($tag['type'])?$tag['type']:'';
        $name = isset($tag['name'])?$tag['name']:'';
        $required = isset($tag['required'])?$tag['required']:'';
        $default = isset($tag['default'])?$tag['default']:'';
        $class = isset($tag['class'])?$tag['class']:'';

        if (empty($code))return '字典编码不能为空';
        if (empty($type))return 'HTML标签类型不能为空';

        $data = Dictionary::get(['code'=>$code]);
        $inputStr = '';
        switch ($type){
            case 'select':
                $inputStr = '<select class="'.$class.'" name="'.$name.'" lay-verify="'.$required.'">';
                $inputStr .= '<option value=""></option>';
                foreach ($data->dictionaryItem as $k=>$v){
                    $inputStr .= '<option value="'.$v['id'].'" {in name="'.$v['id'].'" value="'.$default.'"}selected{/in}>'.$v['name'].'</option>';
                }
                $inputStr .= '</select>';
                break;
            case 'radio':
                foreach ($data->dictionaryItem as $k=>$v){
                    $inputStr .= '<input lay-verType="tips" lay-verify="'.$required.'" '.$required.' type="radio" value="'.$v['id'].'" name="'.$name.'" title="'.$v['name'].'" {in name="'.$v['id'].'" value="'.$default.'"}checked{/in}>';
                }
                break;
            case 'checkbox':
                foreach ($data->dictionaryItem as $k=>$v){
                    $inputStr .= '<input lay-verify="'.$required.'" type="checkbox" value="'.$v['id'].'" name="'.$name.'[]" title="'.$v['name'].'" {in name="'.$v['id'].'" value="'.$default.'"}checked{/in}>';
                }
                break;
            default:
                return '';
        }
        return  $inputStr;
    }
}
